package SwingUiChatting;

import chattingRoom.ReleaseUtils;
import chattingRoomNIO.Client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 对原来的服务端进行封装，方法抽取
 */
public class ChatServerUpdate {
    //创建一个并发的容器，就是在你适用对象的同时，也可以对对象进修改
    //列表里面的
    private static CopyOnWriteArrayList<Channel> users=new CopyOnWriteArrayList<Channel>();
    //加上了静态之后就变成了全局可以调用了
    private  static   ClientSwingUI clientSwingUI=new ClientSwingUI();

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket=new ServerSocket(8888);
        Vector<String> userList=new Vector<>();
        //阻塞式
        while (true) {

            Socket client = serverSocket.accept();
            System.out.println("一个客户端连接了");
            //此时收到了用户的连接 创建线程并且放到容器中去
            Channel newUserchannel=new Channel(client);
            users.add(newUserchannel);
            //实现多线程的功能
            new Thread(newUserchannel).start();

            userList.add(newUserchannel.username);

            //将用户的列表更新一下
            clientSwingUI.userList.setListData(userList);



           /* String applicationMessage = clientSwingUI.getInput();
            System.out.println(applicationMessage);
            //在输入框里面得到了系统发送的消息
            newUserchannel.sendMessageToOthers(applicationMessage,true);
            String userMessage = newUserchannel.reciveMessage();
            userMessage=newUserchannel.username+"对大家说:"+userMessage;*/
            //clientSwingUI.showMsg("hello");

        }


    }


    public  static class Channel implements Runnable{
        private DataOutputStream dataOutputStream;
        private DataInputStream dataInputStream;
        private boolean isRunning;
        private Socket client;
        private String username;




        //定义自己的接收方法
        public Channel(Socket client){
            this.client=client;
            //出现一个连接就添加一个用户
            try {
                dataOutputStream=new DataOutputStream(client.getOutputStream());
                dataInputStream=new DataInputStream(client.getInputStream());
                isRunning=true;
                //管道以及建立好了
                this.username = reciveMessage();
                sendMessage("欢迎来到聊天室");
                clientSwingUI.recordPane.append(username+"来到了聊天室\n");
                sendMessageToOthers(username+"来到了聊天室",true);
            } catch (IOException e) {
                e.printStackTrace();
                release();
                System.out.println("初始化的时候报错");
            }

        }


        public String reciveMessage(){
            String message="";
            try {
                message = dataInputStream.readUTF();
            } catch (IOException e) {
                //如果连接断了失败就要释放资源，不然会一直报错
                release();
                e.printStackTrace();
                System.out.println("接收信息发生错误");
            }
            return message;
        }

        public void sendMessage(String message){
            try {
                dataOutputStream.writeUTF(message);
                dataOutputStream.flush();
            } catch (IOException e) {

                System.out.println("发送信息的过程出现了错误");
            }
        }

        /**
         * 将消息发送给群聊里面的其他人  群聊功能
         * 私聊 默认格式 @xxx:msg
         * @param message
         */
        private void sendMessageToOthers(String message,boolean isSystemMessage){
            boolean isPrivate;//判断是否为私聊的信息
            isPrivate=message.startsWith("@");
            if (isPrivate){
                //得到目标用户名
                int firstShow = message.indexOf(":"); //第一次出现：
                String targetName = message.substring(1, firstShow);
                String privateMessage = message.substring(firstShow + 1);
                //查找用户
                for (Channel user : users) {
                    if (user.username.equals(targetName)){
                        //调用每个线程服务器里面的对象方法
                        user.sendMessage(this.username+"悄悄对你说："+privateMessage);
                    }
                }

            }else {
                for (Channel user : users) {
                    if (user == this) {
                        continue;
                    }
                    //调用每个线程里面的发送给客户端信息的方法
                    if (!isSystemMessage) {
                        //不是系统消息
                        user.sendMessage(this.username + "对所有人说：" + message);
                    } else {
                        user.sendMessage("系统消息：" + message);
                    }

                }
            }
        }

        public void release(){
            this.isRunning=false;
            ReleaseUtils.close(dataInputStream,dataOutputStream,client);
            //将当前的对象用户移除用户群
            users.remove(this);
            //告诉大家某人退出了群聊
            sendMessageToOthers(this.username+"退出了群聊",true);
        }




        @Override
        public void run() {
            while (isRunning){
                String message = reciveMessage();
                if (!message.equals("")){
                    System.out.println(message);
                    if (message.startsWith("@"))
                    {
                        continue;
                    }else {
                        clientSwingUI.recordPane.append(username+"对大家说："+ message+"\n");
                    }

                    //群聊发送
                    sendMessageToOthers(message,false);
                }
                String serverMessage = clientSwingUI.getInput();
                if (!serverMessage.equals("")){
                    //如果输入框里面的信息不为空，那么就群发给大家
                    sendMessageToOthers(serverMessage,true);
                    clientSwingUI.recordPane.append("系统消息："+serverMessage+"\n");
                }
            }
        }
    }
}
